import { Modal, Toast, Select } from "@douyinfe/semi-ui";
import { useEffect, useState } from "react";
import { useRequest } from "ahooks";
import { findAllDrawdbUser, share, getShare } from "../../../api/request";

const Sharing = (props) => {
  const { visible, onCancel, drawdbDataId } = props;
  const [selectData, setSelectData] = useState([]);

  const { run: shareRun, loading: shareLoading } = useRequest(share, {
    manual: true,
    onSuccess() {
      Toast.success("保存成功");
      setSelectData([]);
      onCancel();
    },
  });

  const { run: getShareRun } = useRequest(getShare, {
    manual: true,
    onSuccess(result) {
      setSelectData(result.data?.map((item) => item.shareUserId + ""));
    },
  });

  const { data: userData } = useRequest(findAllDrawdbUser);

  useEffect(() => {
    if (visible) {
      getShareRun(drawdbDataId);
    }
  }, [visible, drawdbDataId, getShareRun]);

  return (
    <Modal
      title="共享用户"
      visible={visible}
      onCancel={onCancel}
      confirmLoading={shareLoading}
      onOk={() => {
        if (selectData.length == 0) {
          Toast.error("请选择共享用户");
          return;
        }

        const userData = JSON.parse(localStorage.getItem("userData"));
        const allData = selectData.map((item) => {
          return {
            shareUserId: item,
            drawdbUserId: userData.id,
            drawdbDataId,
          };
        });
        shareRun(allData);
      }}
    >
      <Select
        multiple
        className="w-full"
        filter
        placeholder="选择共享的用户"
        value={selectData}
        onChange={(data) => setSelectData(data)}
      >
        {userData?.data?.map((item) => (
          <Select.Option key={item.id} value={item.id}>
            {item.userName}
          </Select.Option>
        ))}
      </Select>
    </Modal>
  );
};

export default Sharing;
